#!/usr/bin/env python3
# -*- coding: utf-8
"""
知识库管理API路由
提供PDF导入、知识库搜索和管理功能
"""

from fastapi import APIRouter, HTTPException, BackgroundTasks
from pydantic import BaseModel
from typing import List, Dict, Any, Optional
import os
from services.pdf_import_service import create_pdf_import_service
from utils.logger import emobot_logger

logger = emobot_logger.get_logger()

# 创建路由器
router = APIRouter(prefix="/api/knowledge", tags=["知识库管理"])

# 请求模型
class PDFImportRequest(BaseModel):
    """PDF导入请求"""
    folder_path: str
    chunk_size: int = 1000
    chunk_overlap: int = 200

class SinglePDFImportRequest(BaseModel):
    """单个PDF导入请求"""
    pdf_path: str
    chunk_size: int = 1000
    chunk_overlap: int = 200

class KnowledgeSearchRequest(BaseModel):
    """知识库搜索请求"""
    query: str
    limit: int = 3
    similarity_threshold: float = 0.7

# 响应模型
class ImportResponse(BaseModel):
    """导入响应"""
    success: bool
    message: str
    data: Optional[Dict[str, Any]] = None

class SearchResponse(BaseModel):
    """搜索响应"""
    success: bool
    results: List[Dict[str, Any]]
    total_count: int

class StatsResponse(BaseModel):
    """统计响应"""
    success: bool
    stats: Dict[str, Any]


@router.post("/import-folder", response_model=ImportResponse)
async def import_pdf_folder(request: PDFImportRequest, background_tasks: BackgroundTasks):
    """
    导入PDF文件夹到知识库
    
    Args:
        request: PDF导入请求
        background_tasks: 后台任务
        
    Returns:
        导入结果
    """
    try:
        logger.info(f"开始导入PDF文件夹: {request.folder_path}")
        
        # 验证文件夹路径
        if not os.path.exists(request.folder_path):
            raise HTTPException(status_code=400, detail=f"文件夹不存在: {request.folder_path}")
        
        # 创建PDF导入服务
        pdf_service = create_pdf_import_service(
            chunk_size=request.chunk_size,
            chunk_overlap=request.chunk_overlap
        )
        
        # 执行导入
        result = pdf_service.import_pdf_folder(request.folder_path)
        
        if result.get("success"):
            return ImportResponse(
                success=True,
                message=f"成功导入 {result.get('successful_files', 0)} 个文件，生成 {result.get('total_chunks', 0)} 个文本块",
                data=result
            )
        else:
            return ImportResponse(
                success=False,
                message=f"导入失败: {result.get('error', '未知错误')}",
                data=result
            )
            
    except Exception as e:
        logger.error(f"导入PDF文件夹失败: {e}")
        raise HTTPException(status_code=500, detail=f"导入失败: {str(e)}")


@router.post("/import-single", response_model=ImportResponse)
async def import_single_pdf(request: SinglePDFImportRequest):
    """
    导入单个PDF文件到知识库
    
    Args:
        request: 单个PDF导入请求
        
    Returns:
        导入结果
    """
    try:
        logger.info(f"开始导入单个PDF文件: {request.pdf_path}")
        
        # 验证文件路径
        if not os.path.exists(request.pdf_path):
            raise HTTPException(status_code=400, detail=f"文件不存在: {request.pdf_path}")
        
        if not request.pdf_path.lower().endswith('.pdf'):
            raise HTTPException(status_code=400, detail="不是PDF文件")
        
        # 创建PDF导入服务
        pdf_service = create_pdf_import_service(
            chunk_size=request.chunk_size,
            chunk_overlap=request.chunk_overlap
        )
        
        # 执行导入
        result = pdf_service.import_single_pdf(request.pdf_path)
        
        if result.get("success"):
            return ImportResponse(
                success=True,
                message=f"成功导入文件 {result.get('file_name', '')}，生成 {result.get('total_chunks', 0)} 个文本块",
                data=result
            )
        else:
            return ImportResponse(
                success=False,
                message=f"导入失败: {result.get('error', '未知错误')}",
                data=result
            )
            
    except Exception as e:
        logger.error(f"导入单个PDF文件失败: {e}")
        raise HTTPException(status_code=500, detail=f"导入失败: {str(e)}")


@router.post("/search", response_model=SearchResponse)
async def search_knowledge(request: KnowledgeSearchRequest):
    """
    在知识库中搜索相关内容
    
    Args:
        request: 搜索请求
        
    Returns:
        搜索结果
    """
    try:
        logger.info(f"搜索知识库: '{request.query[:50]}...'")
        
        # 创建PDF导入服务
        pdf_service = create_pdf_import_service()
        
        # 执行搜索
        results = pdf_service.search_knowledge(
            query=request.query,
            limit=request.limit,
            similarity_threshold=request.similarity_threshold
        )
        
        return SearchResponse(
            success=True,
            results=results,
            total_count=len(results)
        )
        
    except Exception as e:
        logger.error(f"知识库搜索失败: {e}")
        raise HTTPException(status_code=500, detail=f"搜索失败: {str(e)}")


@router.get("/stats", response_model=StatsResponse)
async def get_knowledge_base_stats():
    """
    获取知识库统计信息
    
    Returns:
        统计信息
    """
    try:
        logger.info("获取知识库统计信息")
        
        # 创建PDF导入服务
        pdf_service = create_pdf_import_service()
        
        # 获取统计信息
        stats = pdf_service.get_knowledge_base_stats()
        
        return StatsResponse(
            success=True,
            stats=stats
        )
        
    except Exception as e:
        logger.error(f"获取知识库统计信息失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")


@router.delete("/clear")
async def clear_knowledge_base():
    """
    清空知识库
    
    Returns:
        清空结果
    """
    try:
        logger.info("清空知识库")
        
        # 创建PDF导入服务
        pdf_service = create_pdf_import_service()
        
        # 清空知识库
        success = pdf_service.clear_knowledge_base()
        
        if success:
            return {"success": True, "message": "知识库已清空"}
        else:
            return {"success": False, "message": "清空知识库失败"}
            
    except Exception as e:
        logger.error(f"清空知识库失败: {e}")
        raise HTTPException(status_code=500, detail=f"清空失败: {str(e)}")


@router.get("/health")
async def health_check():
    """
    知识库健康检查
    
    Returns:
        健康状态
    """
    try:
        # 创建PDF导入服务
        pdf_service = create_pdf_import_service()
        
        # 获取统计信息作为健康检查
        stats = pdf_service.get_knowledge_base_stats()
        
        return {
            "success": True,
            "status": "healthy",
            "stats": stats
        }
        
    except Exception as e:
        logger.error(f"知识库健康检查失败: {e}")
        return {
            "success": False,
            "status": "unhealthy",
            "error": str(e)
        }
